import { useEffect, useMemo, useState } from 'react';
import { Popover } from 'antd';
import ButtonCommon from './ButtonCommon';
import { ICmdProps } from './type';
import { useCmdStore } from '@/common/store/cmdStore';
import { toolbarMamager } from '@/common/managers/toolbarMamager';
import { useUpdateEffect } from 'ahooks';

interface IProps {
  cmd: ICmdProps;
}
export default function CmdButton({ cmd }: IProps) {
  const { independent, mutualExclusion } = useCmdStore();
  const [open, setOpen] = useState(false);
  useEffect(() => {
    cmd.subscribeDisabled?.(setDisabled);
    cmd.subscribeSelected?.(handleClickLeft);
    toolbarMamager.addToolbarCmds(cmd);
    if (cmd.defaultSelected) {
      handleClickLeft(true);
    }
  }, []);
  const [disabled, setDisabled] = useState(!!cmd?.initialDisabled);
  const onClose = () => {
    setOpen(false);
  };
  const active = useMemo(() => {
    return toolbarMamager.isActive(cmd?.group, cmd.id);
  }, [independent, mutualExclusion]);

  useUpdateEffect(() => {
    toolbarMamager.changeToolbarCmds(active, cmd);
  }, [active]);

  const content = <div>{cmd?.create?.(cmd.label, onClose)}</div>;
  const handleClickLeft = (isActive?: boolean, keep?: boolean) => {
    switch (cmd?.button) {
      case 'independent':
        toolbarMamager.changeIndependent(cmd.id, isActive, keep ?? false);
        break;
      case 'mutualExclusion':
        toolbarMamager.setMutualExclusion(
          cmd.group,
          isActive === false ? '' : cmd.id,
        );
        break;
      case 'btnClick':
        toolbarMamager.changeToolbarCmds(true, cmd);
        break;
    }
  };

  return (
    <Popover
      rootClassName={'_self_popover_content'}
      trigger='click'
      placement='topLeft'
      arrow={false}
      open={open}
      onOpenChange={(value) => {
        if (!value) {
          setOpen(false);
        }
      }}
      getPopupContainer={() => document.querySelector('#app-nextshape_root')}
      content={content}>
      <ButtonCommon
        onClick={(value) => {
          value === 'left' && handleClickLeft();
          value === 'right' && setOpen(!open);
        }}
        popoverOpen={open}
        icon={cmd.icon}
        active={active}
        disabled={disabled}
        label={cmd.label}
        hasRightIcon={!!cmd.create}
        tips={cmd.tips}
        buttonType={cmd.button}
      />
    </Popover>
  );
}
